package com.zeng.stpro.modules.security.filter;

import com.zeng.stpro.commons.utils.Constant;
import com.zeng.stpro.commons.utils.JwtUtils;
import com.zeng.stpro.modules.app.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class TokenAuthFilter extends BasicAuthenticationFilter {

    private RedisTemplate redisTemplate;
    private SysMenuMapper sysMenuMapper;


    public TokenAuthFilter(AuthenticationManager authenticationManager, RedisTemplate redisTemplate, SysMenuMapper sysMenuMapper) {
        super(authenticationManager);
        this.redisTemplate = redisTemplate;
        this.sysMenuMapper = sysMenuMapper;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //过滤静态页面

        //获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        //判断如果有权限信息，放到权限上下文中
        if(authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        chain.doFilter(request,response);
    }
//eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSigwPKkkMN7FV0lFKrShQsjI0MzQyNzeztLSoBQA_WrBGIwAAAA.NbcQhHAvJJfe00zNsTGAUWadoC7h_kDIKEm-OZsL3cRfDWSZNLwPtjkv10h7RoQL1ycD3MLfBfi54Hz0hsaYng
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //从header获取token
        String token = request.getHeader(Constant.TOKEN);
        if(token != null) {
            //从token获取用户名
            String username = JwtUtils.parseToken(token);
            //从redis获取对应权限列表
            //List<String> permissionValueList = (List<String>)redisTemplate.opsForValue().get(username);
            List<String> permissionValueList = (List<String>) redisTemplate.opsForHash().get(username, Constant.RedisHashKey.PROMS.val());

            //Map<String, Object> mappermissionValueList = (Map<String, Object>) request.getSession().getAttribute(username);
            //List<String> permissionValueList = (List<String>) mappermissionValueList.get(Constant.RedisHashKey.PROMS.val());

            // 测试使用
            //List<String> permissionValueLise = sysMenuMapper.findPermissionValueListByUsername(username);
            Collection<GrantedAuthority> authority = new ArrayList<>();
            for(String permissionValue : permissionValueList) {
                if(StringUtils.isEmpty(permissionValue)) continue;
                SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
                authority.add(auth);
            }
            return new UsernamePasswordAuthenticationToken(username,token,authority);
        }
        return null;
    }

}
